import { BASE_API_URL,CONSOLE_REQUEST_ENABLE, CONSOLE_RESPONSE_ENABLE } from '../index.js'
import qs from 'qs'
import store from '@plugins/store'



export  function requestSuccessFunc( requestObj ) {
	// 自定义请求拦截逻辑，可以处理权限，请求发送监控等
	if ( requestObj.method === 'post' ) {
	  
    // if( requestObj.data.service && requestObj.data.service !== 'app.system.getAppToken'   ){
      // console.log(app_token);
    //  	var res = api.common.getAppToken().then(res=>{
    //     store.commit( 'app/SET_APP_TOKEN', res.data );
    //     return res.data;
    //   });
		// }

		var base_data = {
      };
		requestObj.data = qs.stringify( Object.assign(requestObj.data,base_data) )
	}
	if( !_.startsWith(requestObj.url, 'http') ){
    requestObj.url = BASE_API_URL+requestObj.url;
  }
	CONSOLE_REQUEST_ENABLE && console.info( `Req url: ${requestObj.url}`, requestObj );
	return requestObj
}

export function requestFailFunc( requestError ) {
	// 自定义发送请求失败逻辑，断网，请求发送监控等
	// ...

	return Promise.reject( requestError )
}

export function responseSuccessFunc( responseObj ) {
	// 自定义响应成功逻辑，全局拦截接口，根据不同业务做不同处理，响应成功监控等
	// ...
	// 假设我们请求体为
	// {
	//     ret: 1010,
	//     msg: 'this is a msg',
	//     data: null
	// }
	CONSOLE_RESPONSE_ENABLE && console.log( `Resp url: ${responseObj.config.url}`, responseObj )
	let resData = responseObj.data;
	let resStatus = responseObj.status;
	let code = resData.code;
	let data = resData.data;
	if( data &&  !_.isEmpty(data._redirect_url) ){
		location.href = data._redirect_url;
	}
	switch ( code ) {
		case 0: // 如果业务成功，直接进成功回调
			return resData;
		case 21: // user_token
		case 22:
		case 24:
			// 如果业务失败，根据不同 code 做不同处理
			// 比如最常见的授权过期跳登录
			// 特定弹窗
			// 跳转特定页面等

			// location.href = xxx // 这里的路径也可以放到全局配置里
			return;
		default:
			// 业务中还会有一些特殊 code 逻辑，我们可以在这里做统一处理，也可以下方它们到业务层
			// !responseObj.config.noShowDefaultError && Message.info({
			// 	content: msg
			// });
			return Promise.reject( resData );
	}
}

export function responseFailFunc( responseError ) {
	// 响应失败，可根据 responseError.message 和 responseError.response.status 来做监控处理
	// ...
	console.log(responseError);
  var config = responseError.config;

  // If config does not exist or the retry option is not set, reject
  if(!config || !config.retry) return Promise.reject(responseError);

  // Set the variable for keeping track of the retry count
  config.__retryCount = config.__retryCount || 0;

  // Check if we've maxed out the total number of retries
  if(config.__retryCount >= config.retry) {
    // Reject with the error
    return Promise.reject(err);
  }
  // Increase the retry count
  config.__retryCount += 1;

  // Create new promise to handle exponential backoff
  var backoff = new Promise(function(resolve) {
    setTimeout(function() {
      resolve();
    }, config.retryDelay || 1);
  });

  // Return the promise in which recalls axios to retry the request
  return backoff.then(function() {
    return axios(config);
  });
}
